<?php

namespace Wechat\Controller;

class ActivityController extends CommonController {

    /**
     * 活动列表页
     */
    public function index() {
        $categoryId = isNullOrEmpty($_REQUEST["categoryId"]) ? "0" : $_REQUEST["categoryId"];
        $this->assign("categoryId", $categoryId);
        $this->display("index");
    }

    public function academy() {
        $this->display("academy");
    }

    public function activityList() {

        $categoryId = I("post.categoryId");
        $type = I("post.type");

        if(!isNullOrEmpty($categoryId)) {
            $map["category_id"] = $categoryId;
        }
        if(!isNullOrEmpty($type)) {
            $map["activity_type"] = $type;
            $list = D("Activity")
                ->where($map)
                ->order("activity_id desc")
                ->select();
        }else{
            $list = D("Activity")
                ->where($map)
                ->order("begin_time desc")
                ->select();
        }



        foreach ($list as &$item) {
            $item["day"] = date("m月d日 H:i", strtotime($item["begin_time"]));
            $item["time"] = "- ".date("m月d日 H:i", strtotime($item["end_time"]));
        }

        echo json_encode($list);

    }

    /**
     * 报名页面
     */
    public function activityPay() {

        $id = $_REQUEST["id"];

        $activity = D("Activity")->queryById($id);

        if($activity["status"] != C("ACTIVITY_STATUS.WAITING_JOIN")) {
            $this->redirect(U("activity/index"));
        }

        $joinMap["activity_id"] = $id;
        $joinMap["customer_id"] = $this->customer["customer_id"];

        $join = D("ActivityJoin")->queryByMap($joinMap);

        if($join["status"] == C("ACTIVITY_STATUS.WAITING_JOIN")) {
            $this->assign("join", $join);
        }

        $this->assign("appId", C("appid"));
        $this->assign("config", $this->signature());
        $this->assign("activity", $activity);
        $this->display("join");

    }

    /**
     * 报名活动
     */
    public function join() {

        $id = I("post.id");
        $activity = D("Activity")->queryById($id);

        $data["code"] = 200;

        if(isNullOrEmpty($activity)) {
            $data["code"] = -1;
            $data["msg"] = "活动不存在";
            echo json_encode($data);
            exit();
        }

        if($activity["status"] != C("ACTIVITY_STATUS.WAITING_JOIN")) {
            $data["code"] = -2;
            $data["msg"] = "对不起，当前活动不可报名";
            echo json_encode($data);
            exit();
        }

        $joinMap["activity_id"] = $id;
        $joinMap["customer_id"] = $this->customer["customer_id"];

        $join = D("ActivityJoin")->queryByMap($joinMap);

        if(isNullOrEmpty($join)) {

            $payId = D('Pay')->add(array(
                'out_trade_no' => time() . rand(0, 999),
                'money' => $activity['price'],
                'status' => 0,
                'callback' => "",
                'create_time' => getCurrentDate(),
                'update_time' => getCurrentDate(),
                'pay_source' => 1
            ));

            $joinData["customer_id"] = $this->customer["customer_id"];
            $joinData["create_time"] = getCurrentDate();
            $joinData["activity_id"] = $id;
            if($activity['activity_pay'] == 1)
                $joinData["status"] = C("ACTIVITY_JOIN_STATUS.WAITING_PAY");
            else
                $joinData["status"] = C("ACTIVITY_JOIN_STATUS.END_PAY");
            $joinData["name"] = I("post.name");
            $joinData["contact"] = I("post.contact");
            $joinData["idcard"] = I("post.idcard");
            $joinData["company"] = I("post.company");
            $joinData["need_invoice"] = I("post.needInvoice");
            $joinData["invoice_name"] = I("post.invoiceName");
            $joinData["invoice_address"] = I("post.invoiceAddress");
            $joinData["pay_id"] = $payId;

            D("ActivityJoin")->add($joinData);

        } else {

            if($join["status"] != C("ACTIVITY_JOIN_STATUS.WAITING_PAY")) {
                $data["code"] = -3;
                $data["msg"] = "对不起，当前活动已经报名";
                echo json_encode($data);
                exit();
            }

            $join["name"] = I("post.name");
            $join["contact"] = I("post.contact");
            $join["idcard"] = I("post.idcard");
            $join["company"] = I("post.company");
            $join["need_invoice"] = I("post.needInvoice");
            $join["invoice_name"] = I("post.invoiceName");
            $join["invoice_address"] = I("post.invoiceAddress");

            D("ActivityJoin")->updateInfo($join);

            $payId = $join["pay_id"];

        }

        //免费报名
        if($activity['activity_pay'] !=  C("ACTIVITY_PAY.YES")){
            //修改已经报名人数
            $paidMap["activity_id"] = $activity["activity_id"];
            $paidMap["status"] = C("ACTIVITY_JOIN_STATUS.END_PAY");
            $paidCount = D("ActivityJoin")->where($paidMap)->count();
            $activity["join_number"] = $paidCount;

            if($activity["upper_limit"] <= $paidCount
                && $activity["status"] == C("ACTIVITY_STATUS.WAITING_JOIN")) {
                $activity["status"] = C("ACTIVITY_STATUS.FULL");
            }

            D("Activity")->updateInfo($activity);

            $data["code"] = 0;
            $data["msg"] = "报名成功";
            echo json_encode($data);
            exit();
        }

        //收费报名
        $pay = D("Pay")->queryById($payId);

        //支付相关
        $arr = array(
            'appid' => C('appid'),
            'mch_id' => C('mch_id'),
            'nonce_str' => $this->createNoncestr(),
            //'sign' => '',	//签名
            'body' => "希卫康活动报名",
            'out_trade_no' => $pay['out_trade_no'], //订单号
            'total_fee' => $pay['money'] * 100, //金额
            'spbill_create_ip' => get_client_ip(),
            'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].'/Wechat/Api/handlePayActivity', //通知地址
            'trade_type' => 'JSAPI',
            'openid' => $this->customer['openid'],
        );

        $arr['sign'] = $this->getSign($arr);  //签名

        $post = curl('https://api.mch.weixin.qq.com/pay/unifiedorder', $this->arrayToXml($arr));

        $arr2 = $this->xmlToArray($post);

        $jsApiObj["appId"] = C('appid');
        $timeStamp = time();
        $jsApiObj["timeStamp"] = "$timeStamp";
        $jsApiObj["nonceStr"] = $this->createNoncestr();
        $jsApiObj["package"] = "prepay_id=" . $arr2['prepay_id'];
        $jsApiObj["signType"] = "MD5";
        $jsApiObj["paySign"] = $this->getSign($jsApiObj);

        $data["webarr"] = $jsApiObj;

        echo json_encode($data);

    }

    /**
     * 活动详情页
     */
    public function detail() {

        $id = $_REQUEST["id"];
        $activity = D("Activity")->queryById($id);

        if(isNullOrEmpty($activity)) {
            $this->redirect(U("activity/index"));
        }

        if($activity["activity_type"] == C("ACTIVITY_TYPE.THIRD_PARTY")) {
            $this->redirect(U("activity/index"));
        }

        $activity["day"] = date("m月d日 H:i", strtotime($activity["begin_time"]));
        $activity["time"] = "- ".date("m月d日 H:i", strtotime($activity["end_time"]));

        $activity["day_gap"] = calculateDayGapByTimeStr(
            getCurrentDate(), $activity["begin_time"]);

        if($activity["day_gap"] < 0) {
            $this->assign("end", 1);
        } elseif($activity["day_gap"] == 0) {
            $activity["day_gap"] = "0";
        }

        $joinMap["customer_id"] = $this->customer["customer_id"];
        $joinMap["activity_id"] = $id;
        $joinMap["status"] = C("ACTIVITY_JOIN_STATUS.END_PAY");

        $join = D("ActivityJoin")->queryByMap($joinMap);

        $this->assign("customer", $this->customer);
        $this->assign("joined", !isNullOrEmpty($join));
        $this->assign("activity", $activity);
        $this->display("detail");

    }

    
}